<?php


namespace app\common\controller;

use app\api\model\CompanyAgent;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use custom\Redis;
use custom\Token;
use think\App;
use think\Exception;
use think\facade\Request;

class ApiController extends BaseController {

    const DEFAULT_CODE = 510100;
    protected $isSign = true;
    protected $isEncrypt = true;
    protected $headersFields = ['adcode', 'token', 'os', 'over', 'version', 'devsn', 'registrationid'];

    public function initialize(App $app = null) {
        if (!Request::isPost()) {
            $this->resErr('request fail', RespCode::PARAMS_ERR);
        }
        parent::initialize($app);
    }

    /**
     * 权限验证
     */
    protected function auth() {
        if (!in_array('*', $this->notNeedPhone) && !in_array(strtolower($this->request->action()), $this->notNeedPhone)) {
            define('IS_PHONE', 1);
        }
        if (!in_array('*', $this->notNeedToken) && !in_array(strtolower($this->request->action()), $this->notNeedToken)) {
            if (empty($this->headers['token'])) {
                $this->resErr('请登录访问', RespCode::TOKEN_EMPTY);
            }
            $Token = new Token();
            if (!$this->uInfo = $Token->verifyToken($this->headers['token'], $this->headers['devsn'], $Token::API_TOKEN, RedisKey::APP_TOKEN_HASH)) {
                $this->resErr();
            }
            $info=$this->uInfo;
            $headers=$this->headers;
            if ($info['registration_id']!=$headers['registrationid']){

                if (!empty($headers['registrationid'])){
                    //清除设备id
                    CompanyAgent::clearRegistrationid ($headers['registrationid']);
                }
                //更新设备号
                db('company_agent')->where("id",$info['id'])->update(['registration_id'=>$headers['registrationid']]);
            }

            //验证重复提交
            if (in_array(strtolower($this->request->action()), $this->resubmitLock)) {
                $this->resubmitLock($this->uInfo['id'], strtolower($this->request->action()), 1);
            }
        }
    }

    /**
     * 重复提交的锁
     * @param $uid
     * @param $action
     */
    protected function resubmitLock($uid, $action, $ex) {
        $key = $uid . "_{$action}";
        if (!$this->resubmitredis($key, $ex)) {
            $this->resErr('请求太频繁', RespCode::DEFAULT_ERR);
        }
    }

    public function resubmitredis($key, $expire) {
        $redisModel = Redis::getInstance();
        $key = "resubmitLock_$key";
        return $redisModel->set($key, 1, ['nx', 'ex' => $expire]);
    }

    /**
     * 参数验证
     * @param $fields
     * @return mixed
     * @throws Exception
     */
    protected function checkParams($fields) {
        parent::checkParams($fields);
        if (!empty($this->uInfo)) {
            empty($this->params['agent_id']) && $this->params['agent_id'] = $this->uInfo['id'];
        }
        if (empty($this->headers['adcode'])) {
            $adcode = self::DEFAULT_CODE;
        } else {
            $adcode = $this->headers['adcode'];
        }
        !empty($adcode) && empty($this->params['city_code']) && $this->params['city_code'] = $adcode;
        //城市code校验
        $con=$this->request->controller();
        $action=$this->request->action();
        //排除家乡保存接口
        if (!empty($this->uInfo)&&strtolower($con)!=='agent'&&strtolower($action)!=='homesave'){
            $this->checkCity();
        }
        return $this->params;
    }


    /**
     * 校验城市code是否被删除
     * @return false|string
     */
    public function checkCity(){
        $codes=db('company')->where('id',$this->uInfo['company_id'])->where('deleted',0)->value('city_code');
        if (strpos($codes, (string) $this->params['city_code']) === false){
          return  $this->resErr('城市数据已关闭，请登录后重试',RespCode::CITY_CODE_ERR);
        }
    }

}
